package com.example.demo;

import com.github.yhqy.datasource.DataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @author xchen
 * @date 2019/8/6 10:37
 */
@Component
public class DemoDataSourceFactory implements DataSourceFactory {

    @Autowired
    private TestMapper testMapper;

    @Override
    public DataSource createDefaultDataSource() {
        return DataSourceBuilder.create().username("root").password("chenxing")
                .url("jdbc:mysql://localhost:3306/test_common?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8")
                .build();
    }

    @Override
    public DataSource createDataSource(String key) {
        DataSourceDO dataSourceDO = testMapper.getById(Integer.parseInt(key));
        return DataSourceBuilder.create().username(dataSourceDO.getUsername()).password(dataSourceDO.getPassword()).url(dataSourceDO.getUrl()).build();
    }

    @Override
    public String key() {
        return "id";
    }
}
